﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Collections;
using System.Collections.ObjectModel;
using _18miljard.Daily;

namespace _18miljard
{
	public class DataCache
	{
		public static void ClearAll()
		{
			//According to some web resources, we can safely remove items from within the loop, since we are working on a copy of the cache when iterating.
			Cache cache = DataCache.Cache;
			foreach (DictionaryEntry entry in cache)
			{
				cache.Remove((string)entry.Key);
			}
		}

		public static TopBanner TopBanner
		{
			get
			{
				string cacheName = "data_topbanner";

				object obj = DataCache.Cache[cacheName];

				if (obj == null)
				{
					TopBanner topBanner = new TopBanner();

					CacheDependency dependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/TopBanner.xml"));

					DataCache.ExpireNextDay(cacheName, topBanner, dependency);

					obj = topBanner;
				}

				return (TopBanner)obj;
			}
		}

		public static DailyJobs DailyJobs
		{
			get
			{
				string cacheName = "data_dailyjobs";

				object obj = DataCache.Cache[cacheName];

				if (obj == null)
				{
					DailyJobs sendReminder = new DailyJobs();

					CacheDependency dependency = new CacheDependency(HttpContext.Current.Server.MapPath("/App_Data/Daily.xml"));

					DataCache.Cache.Insert(cacheName, sendReminder, dependency);

					obj = sendReminder;
				}

				return (DailyJobs)obj;
			}
		}


		public static Cache Cache
		{
			get { return HttpContext.Current.Cache; }
		}

		public static void ExpireNextDay(string key, object value)
		{
			DataCache.ExpireNextDay(key, value, null);
		}

		public static void ExpireNextDay(string key, object value, CacheDependency dependency)
		{
			DataCache.Cache.Insert(key, value, dependency, DateTime.Today.AddDays(1), Cache.NoSlidingExpiration);
		}
	}
}